<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { useTitle } from '@vueuse/core';
import {
  Button,
  Card,
  Form,
  FormItem,
  Input,
  message,
  Popover,
  Select,
  SelectOption,
} from 'ant-design-vue';

import { getSettingAdmin, putSettingAdmin } from '#/api/admin/setting';
import { $t } from '#/locales';
import { router } from '#/router';
import { usePreferencesStore } from '#/store';

defineOptions({
  name: 'AdminSettingadmin',
});
const form = ref({
  admin_settings: {
    admin_name: '',
    admin_password: 'admin',
    admin_theme: '',
    admin_style: '',
  },
});
const formRef = ref();
const adminStyles = ref([]);
const adminThemes = ref([]);
const host = ref(`${window.location.protocol}//${window.location.host}/`);
const lodadminPassword = ref('admin');
const onSearch = async () => {
  const { data } = await getSettingAdmin();
  if (data.admin_settings) {
    if (data.admin_settings.admin_password) {
      lodadminPassword.value = data.admin_settings.admin_password;
    }
    form.value.admin_settings = data.admin_settings;

    if (data.admin_settings.admin_name === '') {
      const preferencesStore = usePreferencesStore();
      data.admin_settings.admin_name = preferencesStore.title;
    }
  }
  if (data.admin_styles) {
    adminStyles.value = data.admin_styles;
    if (data.admin_settings === null) {
      form.value.admin_settings.admin_style = data.admin_styles[0];
    }
  }
  if (data.admin_themes) {
    adminThemes.value = data.admin_themes;
    if (data.admin_settings === null) {
      form.value.admin_settings.admin_theme = data.admin_themes[0];
    }
  }
};
function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      const { msg } = await putSettingAdmin(form.value);
      message.success({
        content: msg,
      });
      const routeTitle = router.currentRoute.value.meta?.title;
      const preferencesStore = usePreferencesStore();
      preferencesStore.setTitle(form.value.admin_settings.admin_name);
      const pageTitle =
        (routeTitle ? `${$t(routeTitle)} - ` : '') +
        form.value.admin_settings.admin_name;
      useTitle(pageTitle);
      if (lodadminPassword.value !== form.value.admin_settings.admin_password) {
        // 清除前端所有缓存
        localStorage.clear();
        window.location = `${window.location.protocol}//${
          window.location.host
        }/${form.value.admin_settings.admin_password}` as any;
      }
      await onSearch();
    })
    .catch((error: string) => {
      console.error('error', error);
    });
}

onMounted(() => {
  onSearch();
});
</script>

<template>
  <Page>
    <Card>
      <Form
        ref="formRef"
        :label-col="{ style: { width: '150px' } }"
        :model="form"
        :wrapper-col="{ span: 14 }"
        style="max-width: 860px"
      >
        <FormItem :label="$t('page.common.Admin Name')">
          <Input v-model:value="form.admin_settings.admin_name" />
        </FormItem>
        <FormItem :label="$t('page.common.Admin Password')">
          <Input v-model:value="form.admin_settings.admin_password">
            <template #addonAfter>
              <Popover :title="$t('page.common.Usage Instructions')">
                <template #content>
                  <p class="help-block">{{$t('page.common.Letters and numbers, cannot be pure numbers')}}</p>
                  <p class="help-block" style="color: red">
                    {{$t('page.common.paaa')}}
                  </p>
                  <p class="help-block">
                    {{$t('page.common.Admin login URL')}}：
                    <span id="js-site-admin-url">
                      {{ host + form.admin_settings.admin_password }}
                    </span>
                  </p>
                </template>
                <Button type="link">{{$t('page.common.Setup Instructions')}}</Button>
              </Popover>
            </template>
          </Input>
        </FormItem>
        <FormItem :label="$t('page.common.Admin Template')">
          <Select
            v-model:value="form.admin_settings.admin_theme"
            :placeholder="$t('page.common.Please select admin template')"
          >
            <SelectOption
              v-for="(theme, index) in adminThemes"
              :key="index"
              :label="theme"
              :value="theme"
            />
          </Select>
        </FormItem>
        <FormItem :label="$t('page.common.Admin Style')">
          <Select
            v-model:value="form.admin_settings.admin_style"
            :placeholder="$t('page.common.Please select admin style')"
          >
            <SelectOption
              v-for="(style, index) in adminStyles"
              :key="index"
              :label="style"
              :value="style"
            />
          </Select>
        </FormItem>
        <FormItem :wrapper-col="{ span: 14, offset: 4 }">
          <Button type="primary" @click="onSubmit">{{$t('page.common.Save')}}</Button>
        </FormItem>
      </Form>
    </Card>
  </Page>
</template>
